package net.comic.services

import net.comic.entities.*
import net.comic.controllers.*
import net.comic.services.FileService
import org.codehaus.groovy.grails.commons.GrailsResourceUtils

class ComicService {
    boolean transactional = true
    
    def fileService
    def grailsApplication
    
    def addComic(downloadedfile, comicInstance){
    	try {
    		if ( !(new File(comicInstance.getAbsoluteImagePath(comicInstance.name))).exists() ) {
				(new File(comicInstance.getAbsoluteImagePath(comicInstance.name))).mkdir()
			}
    		if(!downloadedfile.isEmpty()) {
    			def validation = fileService.validate(downloadedfile)
        		if(validation.response == "marta") {
        			comicInstance.imagePath = comicInstance.name + validation.ext
        			downloadedfile.transferTo( new File(comicInstance.getAbsoluteImagePath(comicInstance.name) + comicInstance.name +"."+validation.ext) )
        		}
    		} else {
    			comicInstance.imagePath = grailsApplication.config.comics.defaultImageComic
    		}
			comicInstance.save()
    		return [response:"marta", instance:comicInstance]
    		
        }catch (e) {
        	log.error e
        	return [response:"marta"]
		}
    }
    
    
    def delete(comicInstance) {
    	boolean result = false
    	try {
    		//	Borrem el directory y tots els seus fills
    		def path = (new File(grailsApplication.config.comics.getAbsoluteImagePath + comicInstance.name))
			if( path.exists() ) {
				def files = path.listFiles()
				files.each() {
					if(it.isDirectory()) {
						delete(it)
			        } else {
			        	it.delete()
			        }
				}
			}
    		path.delete()
    		comicInstance.delete()
    		result = true
    		//TODO:verificar si les pagines y alternes les borra en cascada
    		
    	} catch (e) {
    		log.error e
    		//TODO: possar error en comicInstance
    	}
    	
    	return result
    }
    
    
    def update(params) {
    	def comicInstance = Comic.get(params.id)
    	if (comicInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (comicInstance.version > version) {
                    comicInstance.errors.rejectValue("version", "comic.optimistic.locking.failure", "Another user has updated this Comic while you were editing")
                    return comicInstance
                }
            }
            comicInstance.properties = params
            comicInstance.save()
        	return comicInstance
        }
        else {
        	return null
        }
    }
}